package com.bpmn.flow.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.bpmn.flow.cmd.TaskCarbonCopyCmd;
import com.bpmn.flow.controller.vo.TaskVo;
import com.bpmn.flow.service.TaskCarbonCopyService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.TaskService;
import org.flowable.task.api.Task;
import org.flowable.task.api.history.HistoricTaskInstance;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author rain
 * @description 任务抄送服务实现类
 * @date 2025年04月18日 16:34
 */
@Slf4j
@Service
public class TaskCarbonCopyServiceImpl implements TaskCarbonCopyService {

    @Resource
    private ManagementService managementService;

    @Resource
    private TaskService taskService;

    @Resource
    private HistoryService historyService;

    @Override
    public void executeTaskCarbonCopy(String taskId, List<String> userIds) {
        // 实例化任务知会Command
        TaskCarbonCopyCmd taskCarbonCopyCmd = new TaskCarbonCopyCmd(taskId, userIds);
        // 通过ManagementService管理服务执行任务知会Command类
        managementService.executeCommand(taskCarbonCopyCmd);
    }

    @Override
    public List<TaskVo> getCarbonCopyTasks(String userId) {
        List<Task> list = taskService.createNativeTaskQuery()
                .sql("select t1.* from ACT_RU_TASK t1 join ACT_RU_IDENTITYLINK t2 on " +
                        "t2.TASK_ID=t1.ID_ and t2.TYPE_='carbonCopy' and " +
                        "t2.USER_ID_=#{userId}")
                .parameter("userId", userId).list();
        return BeanUtil.copyToList(list, TaskVo.class);
    }

    @Override
    public List<TaskVo> getHistoricCarbonCopyTasks(String userId) {
        List<HistoricTaskInstance> list = historyService
                .createNativeHistoricTaskInstanceQuery()
                .sql("select * from ACT_HI_TASKINST t1 join ACT_HI_IDENTITYLINK t2 on " +
                        "t2.TASK_ID=t1.ID_ and t2.TYPE_='carbonCopy' and t2.USER_ID_=#{userId}")
                .parameter("userId", userId).list();
        return BeanUtil.copyToList(list, TaskVo.class);
    }
}